package com.xrit.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.constant.RedisMessageConstant;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.pojo.Order;
import com.xrit.sunnyday.service.OrderMobileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;


@RestController
@RequestMapping("/order")
public class OrderMobileController {
    @Reference
    private OrderMobileService orderMobileService;

    @Autowired
    private JedisPool jedisPool;

    @PostMapping("/submit")
    public Result submit(@RequestBody Map<String,String> orderInfo){
        //获取redis
        Jedis jedis = jedisPool.getResource();
        //手机号码
        String telephone = RedisMessageConstant.SENDTYPE_ORDER + "_" + orderInfo.get("telephone");
        //获取此手机号码在redis里面VALUE
        String code = jedis.get(telephone);
        //没有则让客户重新发送
        if(StringUtils.isEmpty(code)){
            return new Result(false,"请重新发生验证码！");
        }
        //获取前端输入的验证码判断是否输入正确
        if(code.equals(orderInfo.get("telephone"))){
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }

        Order order = orderMobileService.submitOrder(orderInfo);
        //验证成功，删除redis里面存验证码，防止重复提交
        jedis.del(telephone);

        return new Result(true, MessageConstant.ORDER_SUCCESS,order);
    }

    @GetMapping("/findById")
    public Result findById4Detail(Integer id){
        Map<String,Object> orderInfo = orderMobileService.findById4Detail(id);
        return new Result(true,MessageConstant.ORDER_SUCCESS,orderInfo);
    }
}
